package pl.maslany.angielski;

import static pl.maslany.angielski.PropertiesUtil.MAIL_FROM;
import static pl.maslany.angielski.PropertiesUtil.MAIL_HOST;
import static pl.maslany.angielski.PropertiesUtil.MAIL_PASSWD;
import static pl.maslany.angielski.PropertiesUtil.MAIL_PORT;
import static pl.maslany.angielski.PropertiesUtil.MAIL_TO;
import static pl.maslany.angielski.PropertiesUtil.MAIL_USER;

import i18n.I18NResolver;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.HtmlEmail;

public class MainFrame extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;

	public JLabel inputLabel, query, queryText, cntLabel, cnt;
	public AppTextField input;
	public JButton commit;
	JMenu fileMenu;
	JMenuItem help,eng,pol;
	
	TestLoader loader = null;
	TestRecord currentTest;
	int allTests = 0;
	List <String> helpUsage = new ArrayList<String>();
	Font font = new Font("SansSerif", Font.BOLD, 16);

	
	public MainFrame() {
		super("");
		I18NResolver.setLocale(new Locale(System.getProperty("user.language")));
		this.setTitle(I18NResolver.t("app.title"));
		
		this.add(initialize());
		this.setJMenuBar(getMenu());
		repaint();
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {}
		
		this.setPreferredSize(new Dimension(900, 200));
		this.setBounds(50, 50, 900, 200);
		this.setFont(font);
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		pack();
		setVisible(true);
		try {
			loader = new TestLoader();
			allTests = loader.remindedTests();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), "Error reading test data...", 1);
			this.dispose();
		}
		nextTest();
	}
	
	public JPanel initialize() {
		inputLabel = new JLabel("");
		inputLabel.setFont(font);
		cntLabel = new JLabel("");
		cntLabel.setFont(font);
		query = new JLabel("");
		query.setFont(font);
		queryText = new JLabel("");
		queryText.setFont(font);
		input = new AppTextField(null);
		input.setFont(font);
		
		cnt = new JLabel("");
		cnt.setFont(font);
		
		JPanel panel = new JPanel(new GridLayout(3,2));
		panel.add(inputLabel);
		panel.add(query);
		panel.add(queryText);
		panel.add(input);
		panel.add(cntLabel);
		panel.add(cnt);
		panel.setBorder(new EtchedBorder());
		return panel;
	}
	
	public void nextTest() {
		currentTest = loader.nextTest();
		if (currentTest != null) {
			query.setText(currentTest.query);
			input.setRecord(currentTest);
			cnt.setText(String.valueOf(loader.remindedTests()));
		}
		else {
			sendMail();
			JOptionPane.showMessageDialog(this, I18NResolver.t("last.test.message"));
			this.dispose();
		}
	}

	private void sendMail() {
		if (PropertiesUtil.sendEmail()) {
			try {
				Email email = new HtmlEmail();
				email.setHostName(PropertiesUtil.getProperty(MAIL_HOST));
				email.setSmtpPort(Integer.parseInt(PropertiesUtil.getProperty(MAIL_PORT)));
				email.setAuthenticator(new DefaultAuthenticator(PropertiesUtil.getProperty(MAIL_USER), PropertiesUtil.getProperty(MAIL_PASSWD)));
				email.setTLS(true);
				email.setFrom(PropertiesUtil.getProperty(MAIL_FROM));
				email.setSubject(I18NResolver.t("mail.subject"));
				String helpUsageFormatted = "";
				for (String s : helpUsage) {
					helpUsageFormatted = helpUsageFormatted + s + "<br/>";
				}
				email.setMsg("<a style=\"font-style:normal; font-size: x-large\">"+I18NResolver.t("mail.content1") + allTests + "<br/>" + I18NResolver.t("mail.content2") + "<br/>" + helpUsageFormatted+"</a>");
				String receivers = PropertiesUtil.getProperty(MAIL_TO);
				for (String receiver : receivers.split(",")) {
					email.addTo(receiver);
				}
				email.send();
			} catch (Exception e) {
				System.out.println("Email has not been sent: " + e);
			}
			
		}
	}
	
	private JMenuBar getMenu() {
		JMenuBar menuBar = new JMenuBar();
		menuBar.setBorder(new EtchedBorder());
		fileMenu = new JMenu("");
		
		help = new JMenuItem("");
		help.addActionListener(this);

		eng = new JMenuItem("");
		eng.addActionListener(this);

		pol = new JMenuItem("");
		pol.addActionListener(this);
		
		fileMenu.add(help);
		fileMenu.add(eng);
		fileMenu.add(pol);
		menuBar.add(fileMenu);
		

		
		return menuBar;
	}
	
	 public void actionPerformed(ActionEvent e) {
		 if (e.getActionCommand().equals(I18NResolver.t("help.item"))) {
			 helpUsage.add(currentTest.query);
			 StringBuffer answers = new StringBuffer(I18NResolver.t("help.message") + "\n");
			 for (String ans : currentTest.correctAnwers) {
				 answers.append(ans + "\n");
			 }
			 JOptionPane.showMessageDialog(this, answers);
		 } else if (e.getActionCommand().equals("Polski")) {
			 I18NResolver.setLocale(new Locale("PL"));
			 repaint();
		 } else if (e.getActionCommand().equals("English")) {
			 I18NResolver.setLocale(Locale.ENGLISH);
			 repaint();
		 }
    }
	 
	public void repaint() {
		this.setTitle(I18NResolver.t("app.title"));
		inputLabel.setText(I18NResolver.t("input.label"));
		cntLabel.setText(I18NResolver.t("cnt.label"));
		queryText.setText(I18NResolver.t("query.label"));
		fileMenu.setText(I18NResolver.t("file.menu"));
		help.setText(I18NResolver.t("help.item"));
		eng.setText(I18NResolver.t("english.menu.item"));
		pol.setText(I18NResolver.t("polish.menu.item"));
	}
}
